package comWorld.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gjs.tools.JDBC.JDBCTools;

import comWorld.user.UserInfo;
import comWorld.user.UserStatus;
import comWorld.user.manage.UserInfoManage;

/**
 * Application Lifecycle Listener implementation class RequestListener
 *
 */
@WebListener
public class RequestListener implements ServletRequestListener {

    /**
     * Default constructor. 
     */
    public RequestListener() {
    }

	/**
     * @see ServletRequestListener#requestDestroyed(ServletRequestEvent)
     */
    public void requestDestroyed(ServletRequestEvent arg0)  { 
        
    }

	/**
     * @see ServletRequestListener#requestInitialized(ServletRequestEvent)
     */
    public void requestInitialized(ServletRequestEvent event)  { 
        HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
        HttpSession session = request.getSession();
        UserStatus visitorStatus = (UserStatus) session.getAttribute("visitorStatus");
        if (visitorStatus == null) {
        	UserInfo user = null;
        	Cookie[] cookies = request.getCookies();
        	if (cookies != null) {
	        	for (Cookie ck : cookies) {
	            	if (ck.getName().equals("email")) {
	            		user = UserInfoManage.getUserInfo(ck.getValue(), "email");
	            		break;
	            	}
	            }
        	}
        	UserInfoManage.updateUserStatus(session, user);
        }
    }
}
